<template>
  <div class="role-management">
    <a-card>
      <!-- 搜索表单 -->
      <a-form layout="inline" :model="queryParams" class="search-form">
        <a-form-item :label="t('role.roleName')">
          <a-input
            v-model:value="queryParams.roleName"
            :placeholder="t('role.roleName')"
            allow-clear
          />
        </a-form-item>
        <a-form-item :label="t('role.roleCode')">
          <a-input
            v-model:value="queryParams.roleCode"
            :placeholder="t('role.roleCode')"
            allow-clear
          />
        </a-form-item>
        <a-form-item :label="t('role.status')">
          <a-select
            v-model:value="queryParams.status"
            :placeholder="t('role.status')"
            allow-clear
          >
            <a-select-option :value="1">{{ t('common.normal') }}</a-select-option>
            <a-select-option :value="0">{{ t('common.disabled') }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><search-outlined /></template>
              {{ t('common.search') }}
            </a-button>
            <a-button @click="handleReset">
              <template #icon><redo-outlined /></template>
              {{ t('common.reset') }}
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <!-- 操作按钮 -->
      <div class="table-operations">
        <a-space>
          <a-button type="primary" @click="handleAdd">
            <template #icon><plus-outlined /></template>
            {{ t('common.add') }}
          </a-button>
        </a-space>
      </div>

      <!-- 数据表格 -->
      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'success' : 'error'">
              {{ record.status === 1 ? t('common.normal') : t('common.disabled') }}
            </a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleEdit(record)">
                {{ t('common.edit') }}
              </a-button>
              <a-button type="link" size="small" @click="handleAssignPermission(record)">
                {{ t('common.assignPermission') }}
              </a-button>
              <a-button type="link" size="small" @click="handleAssignUser(record)">
                {{ t('role.assignUser') }}
              </a-button>
              <a-popconfirm
                :title="t('common.confirmDelete')"
                :ok-text="t('common.confirm')"
                :cancel-text="t('common.cancel')"
                @confirm="handleDelete(record)"
              >
                <a-button type="link" size="small" danger>
                  {{ t('common.delete') }}
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 角色表单弹窗 -->
    <a-modal
      v-model:visible="formVisible"
      :title="formType === 'add' ? t('common.add') : t('common.edit')"
      @ok="handleFormSubmit"
      @cancel="handleFormCancel"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item :label="t('role.roleName')" name="roleName">
          <a-input
            v-model:value="formData.roleName"
            :placeholder="t('role.roleName')"
          />
        </a-form-item>
        <a-form-item :label="t('role.roleCode')" name="roleCode">
          <a-input
            v-model:value="formData.roleCode"
            :placeholder="t('role.roleCode')"
          />
        </a-form-item>
        <a-form-item :label="t('role.description')" name="description">
          <a-textarea
            v-model:value="formData.description"
            :placeholder="t('role.description')"
            :rows="4"
          />
        </a-form-item>
        <a-form-item :label="t('role.status')" name="status">
          <a-radio-group v-model:value="formData.status">
            <a-radio :value="1">{{ t('common.normal') }}</a-radio>
            <a-radio :value="0">{{ t('common.disabled') }}</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 分配权限弹窗 -->
    <assign-permission
      v-model:visible="assignPermissionVisible"
      :role-id="currentRoleId"
      :default-checked-keys="currentRolePermissions"
      @success="handleAssignPermissionSuccess"
    />

    <!-- 分配用户弹窗 -->
    <a-modal
      v-model:visible="assignUserVisible"
      :title="t('role.assignUser')"
      @ok="handleAssignUserOk"
      @cancel="handleAssignUserCancel"
      :width="800"
    >
      <a-form
        ref="assignUserFormRef"
        :model="assignUserForm"
        :rules="assignUserRules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <a-form-item :label="t('user.title')" name="userIds">
          <a-transfer
            v-model:target-keys="assignUserForm.userIds"
            :data-source="userOptions"
            :titles="[t('user.available'), t('user.assigned')]"
            :render="(item: { key: number; title: string }) => item.title"
            :list-style="{
              width: '300px',
              height: '400px',
            }"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import {
  SearchOutlined,
  RedoOutlined,
  PlusOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'
import type { TablePaginationConfig } from 'ant-design-vue'
import { useI18n } from 'vue-i18n'
import type { RoleInfo, RoleQuery } from '@/types/role.type'
import {
  getRoleList,
  createRole,
  updateRole,
  deleteRole,
  getRolePermissions,
  updateRolePermissions,
  getRoleUsers,
  updateRoleUsers
} from '@/api/role'
import { getUserList } from '@/api/user'
import { getPermissionTree } from '@/api/permission'
import AssignPermission from './components/AssignPermission.vue'

const { t } = useI18n()

// 查询参数
const queryParams = reactive<RoleQuery>({
  current: 1,
  size: 10,
  roleName: '',
  roleCode: '',
  status: undefined
})

// 表格列定义
const columns = [
  {
    title: t('role.roleName'),
    dataIndex: 'roleName',
    key: 'roleName',
    width: 150
  },
  {
    title: t('role.roleCode'),
    dataIndex: 'roleCode',
    key: 'roleCode',
    width: 150
  },
  {
    title: t('role.description'),
    dataIndex: 'description',
    key: 'description',
    width: 200
  },
  {
    title: t('role.status'),
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: t('role.createTime'),
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180
  },
  {
    title: t('common.action'),
    key: 'action',
    fixed: 'right',
    width: 300
  }
]

// 表格数据
const tableData = ref<RoleInfo[]>([])
const loading = ref(false)

// 分页配置
const pagination = reactive<TablePaginationConfig>({
  total: 0,
  current: 1,
  pageSize: 10,
  showSizeChanger: true,
  showQuickJumper: true
})

// 表单相关
const formRef = ref<FormInstance>()
const formVisible = ref(false)
const formType = ref<'add' | 'edit'>('add')
const formData = reactive<Partial<RoleInfo>>({
  roleName: '',
  roleCode: '',
  description: '',
  status: 1
})

// 表单校验规则
const rules = {
  roleName: [
    { required: true, message: t('role.roleNameRequired') }
  ],
  roleCode: [
    { required: true, message: t('role.roleCodeRequired') }
  ]
}

// 权限树相关
const permissionVisible = ref(false)
const permissionTree = ref<any[]>([])
const checkedPermissions = ref<string[]>([])
const currentRoleId = ref<string>('')

// 用户分配相关
const userVisible = ref(false)
const userList = ref<any[]>([])
const selectedUserIds = ref<string[]>([])

// 分配权限相关
const assignPermissionVisible = ref(false)
const currentRolePermissions = ref<number[]>([])

// 分配用户相关
const assignUserFormRef = ref<FormInstance>()
const assignUserVisible = ref(false)
const assignUserForm = reactive({
  roleId: '',
  userIds: [] as number[]
})

// 分配用户校验规则
const assignUserRules = {
  userIds: [{ required: true, message: t('role.selectUserFirst') }]
}

// 用户选项
const userOptions = ref<{ key: number; title: string }[]>([])

// 获取角色列表
const fetchRoleList = async () => {
  loading.value = true
  try {
    const res = await getRoleList(queryParams)
    
    tableData.value = res.records
    pagination.total = res.total
  } catch (error: any) {
    message.error(error.message || t('common.failed'))
  } finally {
    loading.value = false
  }
}

// 获取权限树
const fetchPermissionTree = async () => {
  try {
    const { data } = await getPermissionTree()
    permissionTree.value = data
  } catch (error: any) {
    message.error(error.message || t('common.failed'))
  }
}

// 获取用户列表
const fetchUserList = async () => {
  try {
    const res = await getUserList({ current: 1, size: 1000 })
    userOptions.value = res.records.map(user => ({
      key: user.id,
      title: user.username
    }))
  } catch (error: any) {
    message.error(error.message || t('common.failed'))
  }
}

// 获取角色权限
const fetchRolePermissions = async (roleId: string) => {
  try {
    const { data } = await getRolePermissions(roleId)
    checkedPermissions.value = data
  } catch (error: any) {
    message.error(error.message || t('common.failed'))
  }
}

// 获取角色用户
const fetchRoleUsers = async (roleId: number) => {
  try {
    const res = await getRoleUsers(roleId)
    // 确保返回的数据是数组
    assignUserForm.userIds = Array.isArray(res) ? res : []
  } catch (error: any) {
    message.error(error.message || t('common.failed'))
  }
}

// 搜索
const handleSearch = () => {
  queryParams.current = 1
  fetchRoleList()
}

// 重置
const handleReset = () => {
  queryParams.roleName = ''
  queryParams.roleCode = ''
  queryParams.status = undefined
  handleSearch()
}

// 表格变化
const handleTableChange = (pag: TablePaginationConfig) => {
  queryParams.current = pag.current || 1
  queryParams.size = pag.pageSize || 10
  fetchRoleList()
}

// 新增
const handleAdd = () => {
  formType.value = 'add'
  Object.assign(formData, {
    roleName: '',
    roleCode: '',
    description: '',
    status: 1
  })
  formVisible.value = true
}

// 编辑
const handleEdit = (record: RoleInfo) => {
  formType.value = 'edit'
  const { createTime, updateTime, isDeleted, ...formDataToEdit } = record
  Object.assign(formData, formDataToEdit)
  formVisible.value = true
}

// 删除
const handleDelete = async (record: RoleInfo) => {
  try {
    await deleteRole(record.id)
    message.success(t('common.success'))
    fetchRoleList()
  } catch (error: any) {
    message.error(error.message || t('common.failed'))
  }
}

// 表单提交
const handleFormSubmit = async () => {
  try {
    await formRef.value?.validate()
    const { createTime, updateTime, isDeleted, ...formDataToSubmit } = formData
    if (formType.value === 'add') {
      await createRole(formDataToSubmit)
      message.success(t('role.addSuccess'))
    } else {
      await updateRole(formDataToSubmit)
      message.success(t('role.updateSuccess'))
    }
    formVisible.value = false
    fetchRoleList()
  } catch (error: any) {
    console.error('表单提交失败:', error)
    message.error(error.message || t('common.operationFailed'))
  }
}

// 表单取消
const handleFormCancel = () => {
  formVisible.value = false
  formRef.value?.resetFields()
}

// 设置权限
const handleSetPermission = async (record: RoleInfo) => {
  currentRoleId.value = record.id
  await fetchPermissionTree()
  await fetchRolePermissions(record.id)
  permissionVisible.value = true
}

// 提交权限设置
const handlePermissionSubmit = async () => {
  try {
    await updateRolePermissions(currentRoleId.value, checkedPermissions.value)
    message.success(t('common.success'))
    permissionVisible.value = false
  } catch (error: any) {
    message.error(error.message || t('common.failed'))
  }
}

// 取消权限设置
const handlePermissionCancel = () => {
  permissionVisible.value = false
  checkedPermissions.value = []
  currentRoleId.value = ''
}

// 分配用户
const handleAssignUser = async (record: RoleInfo) => {
  try {
    assignUserForm.roleId = record.id
    await fetchUserList()
    await fetchRoleUsers(record.id)
    assignUserVisible.value = true
  } catch (error: any) {
    message.error(error.message || t('common.failed'))
  }
}

// 分配用户确认
const handleAssignUserOk = async () => {
  try {
    await assignUserFormRef.value?.validate()
    await updateRoleUsers(assignUserForm.roleId, assignUserForm.userIds)
    message.success(t('common.success'))
    assignUserVisible.value = false
  } catch (error: any) {
    if (error.errorFields) {
      return
    }
    message.error(error.message || t('common.failed'))
  }
}

// 分配用户取消
const handleAssignUserCancel = () => {
  assignUserVisible.value = false
  assignUserFormRef.value?.resetFields()
}

// 分配权限
const handleAssignPermission = async (record: RoleInfo) => {
  try {
    currentRoleId.value = record.id
    const res = await getRolePermissions(record.id)
    currentRolePermissions.value = res
    assignPermissionVisible.value = true
  } catch (error: any) {
    message.error(t('common.getRolePermissionsFailed'))
  }
}

// 分配权限成功
const handleAssignPermissionSuccess = () => {
  fetchRoleList()
}

// 初始化
onMounted(() => {
  fetchRoleList()
})
</script>

<style lang="less" scoped>
.role-management {
  .search-form {
    margin-bottom: 16px;
  }

  .table-operations {
    margin-bottom: 16px;
  }
}
</style> 